package org.stvd.common;

import java.util.ArrayList;
import java.util.List;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * 在Spring Security中，获取当前用户的信息
 */
public class SecurityUserHolder {

    /**
     * 获得当前用户详细信息
     */
    public static UserDetails getCurrentUserDetail() {
        try {
            return (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获得当前用户ID
     */
    public static Long getCurrentUserid() {
        try {
            Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            if (principal instanceof UserDetails) {
                return Long.parseLong(((UserDetails) principal).getUsername());
            } else if (principal instanceof Long) {
                return (Long) principal;
            }
        } catch (Exception e) {
        }
        return null;
    }

    /**
     * 获得当前用户的角色
     */
    public static String[] getCurrentUserRoles() {
        UserDetails userDetails = getCurrentUserDetail();
        if (userDetails != null) {
            List<String> list = new ArrayList<String>();
            for (GrantedAuthority ga : userDetails.getAuthorities()) {
                list.add(ga.getAuthority());
            }
            String[] array = new String[list.size()];
            return list.toArray(array);
        }
        return null;
    }
}
